package com.eminem.controller.user.login;

import com.eminem.common.StrMath;
import com.eminem.controller.BaseServlet;
import com.eminem.model.User;
import com.eminem.service.UserService;
import com.eminem.service.impl.UserServletimpl;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login/*")
public class LoginController extends BaseServlet {

    private UserService userService = new UserServletimpl();


    public void login(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        //可以做一个简单的校验判断
        if (null != username && null != password){
            User user = userService.Usercheck(username);
            try {
                if (null != user){
                    if (password.equals(user.getPassword())){
                        //                req.getRequestDispatcher("/html/home.html").forward(req,resp);
                        if (null != remember){
                            Cookie cookie = new Cookie("username", username);
                            cookie.setMaxAge(StrMath.Math_Save_Time);
                            cookie.setPath("/");
                            resp.addCookie(cookie);
                        }
                        Map<String, Object> map = userService.findUserInfo(username);
                        req.getSession().setAttribute("UserInfo",map);
                        req.getSession().setAttribute(req.getSession().getId(),map.get("userId").toString());

                        userService.updateLoginTime(user.getId());

                        resp.sendRedirect(req.getContextPath()+"/html/home.jsp");
//                        System.out.println("登录成功");
                        return;
                    }else {
//                    resp.getWriter().write("<script>window.alert('密码错误');</script>");
                        req.getSession().setAttribute("msg","密码错误");
//                        System.out.println("密码错误");
                    }
                }else {
                    req.getSession().setAttribute("msg","找不到用户名");
//                resp.getWriter().write("<script language='javascript'>window.alert('找不到用户名');</script>");
//                    System.out.println("找不到用户名");
                }
                //重定向回首页
                resp.sendRedirect("/index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                resp.sendRedirect("/index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void register(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            boolean b = userService.cheackNameorEmail(email, username);
            if (!b){
                req.getSession().setAttribute("regmsg","该用户名或者邮箱已被注册");
                resp.sendRedirect("/register.jsp");
            }else {
                if (password.equalsIgnoreCase(password2)){
                    User user = new User();
                    user.setEmail(email);
                    user.setUsername(username);
                    user.setPassword(password);
                    boolean add = userService.addUser(user);
                    if (add){
                        //添加成功
                        req.getSession().setAttribute("msg","注册成功");
                        resp.sendRedirect("/index.jsp");
                        System.out.println("注册成功");
                    }else {
                        req.getSession().setAttribute("regmsg","注册失败");
                        resp.sendRedirect("/register.jsp");
                        System.out.println("注册失败");
                    }
                }else {
                    req.getSession().setAttribute("regmsg","密码不一致，请重新输入");
                    resp.sendRedirect("/register.jsp");
                    System.out.println("密码不一致，请重新输入");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp){
        String email = req.getParameter("email");
        User user = userService.findEmail(email);
        String data = "0";
        if (null != user){
            data = "1";
//            System.out.println("已有邮箱");
        }
        try {
            resp.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void checkUserName(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        User user = userService.Usercheck(username);
        String data = "0";
        if (null != user){
            data = "1";
        }
        try {
            resp.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp){
        try {
            HttpSession session = req.getSession();
            String email = req.getParameter("email");
            User user = userService.findEmail(email);
            if (null == user){
                resp.getWriter().write("该邮箱用户不存在");
            }else {
                Object attribute = session.getAttribute(email);
                if (null == attribute){
                    String code = userService.sendEmailCode(email);
                    System.out.println("验证码是"+code);
                    if (code.length() == 4){
                        session.setAttribute(email,code);
                        session.setMaxInactiveInterval(StrMath.Math_Email_Time);
                        resp.getWriter().write("邮件发送成功");
                    }else {
                        resp.getWriter().write("邮件发送失败");
                    }
                }else {
                    resp.getWriter().write("邮件的验证码已发送，请查收");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reset(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("code");
            String passwoed = req.getParameter("password");
            User user = userService.findEmail(email);
            if (null == user){
                req.getSession().setAttribute("forMsg","该邮箱账号不存在");
                System.out.println("该邮箱账号不存在");
                resp.sendRedirect("/forget.jsp");
            }else {
                Object hcode = req.getSession().getAttribute(email);
                if (null == hcode){
                    req.getSession().setAttribute("forMsg","验证码已过期");
                    System.out.println("验证码已过期");
                    resp.sendRedirect("/forget.jsp");
                }else {
                    if (hcode.toString().equals(code)){
                        boolean b = userService.resetPassword(email,passwoed);
                        if (b) {
                            req.getSession().setAttribute("msg","修改密码成功");
                            System.out.println("修改密码成功");
                            resp.sendRedirect("/index.jsp");
                        }else {
                            req.getSession().setAttribute("forMsg","修改密码失败");
                            System.out.println("修改密码失败");
                            resp.sendRedirect("/forget.jsp");
                        }
                    }else {
                        req.getSession().setAttribute("forMsg","验证码不正确");
                        System.out.println("验证码不正确");
                        resp.sendRedirect("/forget.jsp");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp){
        try {
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }
            }
            resp.sendRedirect(req.getContextPath()+"/index.jsp");

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
